package com.itheima.health.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.UUID;

@Slf4j
@Component
@Data
@ConfigurationProperties("alioss")
public class AliossUtil {

    private String urlPrefix;
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    public String upload(String fileName, InputStream is) {
        String endpoint = urlPrefix + this.endpoint;
        String tailName = fileName.substring(fileName.lastIndexOf("."));
        String objectName = UUID.randomUUID() + tailName;
        LocalDate now = LocalDate.now();
        String finalPath = now.getYear() + "/" + now.getMonthValue() + "/" + now.getDayOfMonth() + "/" + objectName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, finalPath, is);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            log.error("文件上传失败：{}，栈信息：{}", oe.getMessage(), oe.getStackTrace());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        log.info("文件上传成功：{}", finalPath);
        return urlPrefix + bucketName + "." + this.endpoint + "/" + finalPath;
    }
}
